import { Component, OnInit, Input, Output, ChangeDetectorRef, EventEmitter } from '@angular/core';
import { CompanyService } from '../../../../../modules/research/company/company.service';
import { CompanyModel } from '../../../../../modules/research/company/company.model';
import { UtilsService } from '../../../../services/utils.service';
import { LrtmService } from '../../../../../framework/lrtm/lrtm.service';
import { BaseComponent } from '../../../baseComponent/base.component';
import { AppComponent } from '../../../../../app.component';
import { NgxSmartModalService } from 'ngx-smart-modal';
import { ResearchState } from '../../../../../modules/research/research.service';
import { AnalyticsService } from '../../../../services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../../models/googleAnalytics.model';

@Component({
    selector: 'app-search-result',
    templateUrl: './search-result.component.html',
    styleUrls: ['./search-result.component.scss']
})
export class SearchResultComponent extends BaseComponent implements OnInit {
    @Input() company: CompanyModel;
    @Input() term: string;
    @Input() hasAddButton = false;
    @Input() navigationId: string = "searchInput";
    @Output() companyAdded: EventEmitter<string> = new EventEmitter();
    public downloadLinks = [];
    public showDownloads = false;

    constructor(
        private roortComponent: AppComponent,
        private companyService: CompanyService,
        private lrtmService: LrtmService,
        private cdRef: ChangeDetectorRef,
        public ngxSmartModalService: NgxSmartModalService,
        private analyticsService: AnalyticsService
    ) {
        super(cdRef);
    }

    ngOnInit() {
        this.downloadLinks = this.getDownloadLinks();
    }

    public getDownloadLinks() {
        const links = [];
        if (this.productPermissions.riskrating &&
            this.company.hasRiskRatingAccountFeature &&
            (this.company.riskRatingResearchState === ResearchState.ResearchAvailable || this.company.coreRiskResearchState === ResearchState.ResearchAvailable) ) {
            links.push({
                name: 'ESG Risk Rating',
                data: this.companyService.getRiskRatingDownloadData(this.company)
            });
        }

        if (this.productPermissions.esg &&
            this.company.hasEsgAccountFeature &&
            (this.company.coreEsgResearchState === ResearchState.ResearchAvailable || this.company.comprehensiveEsgResearchState === ResearchState.ResearchAvailable)) {
            links.push({
                name: 'ESG Rating',
                data: this.companyService.getEsgDownloadData(this.company)
            });
        }

        if (this.productPermissions.controversies &&
            this.company.hasControversiesAccountFeature &&
            this.company.controversyResearchState === ResearchState.ResearchAvailable) {
            links.push({
                name: 'Controversies',
                data: this.companyService.getControversyDownloadData(this.company)
            });
        }

        if (this.productPermissions.governance &&
            this.company.hasGovernanceAccountFeature &&
            this.company.corporateGovernanceResearchState === ResearchState.ResearchAvailable) {
            links.push({
                name: 'Corporate Governance',
                data: this.companyService.getGovernanceDownloadData(this.company)
            });
        }

        return links;
    }

    public downloadReport(downloadData) {
        // set report name
        const reportName = UtilsService.getCompanyReportName(this.company, downloadData.reportName, false);

        // add isSummary to reportData
        if (downloadData.reportData instanceof Object) {
            downloadData.reportData.isSummaryReport = false;
        }

        //send analytics data
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('SearchBarDownloadPDF', 'Home', { CompanyId: this.company.id, ReportType: downloadData.reportType}));

        // run task
        this.lrtmService.runTask(this.roortComponent, reportName, downloadData.reportType, downloadData.reportData, true)
            .subscribe(_ => { });
    }

    public addCompanyClicked(companyId: string) {
        this.companyAdded.emit(companyId);
    }

    /**
     * Method called when clicking on a company/portfolio to close the modal after navigating
     */
    public closeSearchModal() {
        this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon(
            this.navigationId == 'navigationSearchInput' ? 'Global Navigation Search Bar' : 'Home Page Search Bar',
            'Home', 
            { CompanyId: this.company.id }));

        const modalStack = this.ngxSmartModalService.getModalStack();
        for (let modalInstance of modalStack) {
            if (modalInstance.id === "searchModal") {
                modalInstance.modal.close();
            }
        }
    }

}
